<!--
 * @Author: ljc
 * @Date: 2023-04-25 15:00:24
 * @LastEditors: g05047
 * @LastEditTime: 2023-06-08 20:08:55
 * @Description: 专家擅长自动分配列表
-->

<template>
  <div>
    <rk-dialog width="80%"
      height="70%"
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      @close="handleClose"
      :maskClosable="false">
      <RkContainer :isFooter="false"
        :isAside=false
        :isHeader="false">
        <template #main>
          <RkCenter>
            <template #condition>
              <RkCenter-bar v-show="true">
                <template #content>
                  <el-form ref="form"
                    :inline="true">
                    <span>任务名称：{{ taskName }}</span>
                  </el-form>
                </template>
                <template #buttons>
                </template>
              </RkCenter-bar>
            </template>
            <template #content>
              <rk-grid ref="automaticTableRef"
                dataUrl="/reviewtask/getAssignProjects"
                boxConfig
                :params="queryParams"
                :columns="tableColumns"
                :pagerConfig='false'
                :keepSource="true">
                <template #toolbar_buttons>
                  <rk-tree-select enum="EXPERT_ASSIGN_STATUS"
                    class="w-200px"
                    style="margin-left: 10px;"
                    :filterable="false"
                    :showCode="false"
                    :clearable="false"
                    v-model="queryParams.type"
                    @change="handleSearch">
                  </rk-tree-select>
                </template>
                <template #toolbar_tools>
                  <el-input v-model="queryParams.keyWords"
                    placeholder="请输入项目名称/项目编码"
                    class="w-200px"
                    style="margin-right: 12px;"
                    clearable
                    @input="handleSearch">
                  </el-input>
                  <template v-if="queryParams.type === 0">
                    <el-button style="margin-right: 12px;"
                      type="primary"
                      @click="handleAdd()">
                      指派专家
                    </el-button>
                  </template>
                  <template v-if="queryParams.type === 1">
                    <el-button style="margin-right: 12px;"
                      type="danger"
                      @click="handleCancle('撤销')">
                      撤销
                    </el-button>
                  </template>
                </template>
                <template #expertOperation="{ row }">
                  <el-tag v-for="item in row.expertList"
                    class="expert-tag"
                    :key="item.expertId"
                    :disable-transitions="false">
                    {{ item.name }}
                  </el-tag>
                </template>
              </rk-grid>
            </template>
          </RkCenter>
        </template>
      </RkContainer>
      <template #footer>
        <template v-if="queryParams.type === 0">
          <el-button type="primary"
            @click="handleConfirm('保存')">保存</el-button>
          <el-button @click="handleClose">取消</el-button>
        </template>
        <template v-else>
          <el-button @click="handleClose">取消</el-button>
        </template>
      </template>
    </rk-dialog>
    <project-rule-edit-dialog ref="projectRuleEditDialogRef"
      @save="handleRuleSave"></project-rule-edit-dialog>
    <project-add-expert-dialog ref="projectAddExpertDialogViewRef"
      @save="handleSave"></project-add-expert-dialog>
  </div>
</template>
  <script setup>
import ProjectRuleEditDialog from './ProjectRuleEditDialog.vue'
import ProjectAddExpertDialog from './ProjectAddExpertDialog.vue'
import { RkConfirmBox } from '@/components/message-box/index.js'
import { ref } from 'vue';
import XEUtils from 'xe-utils'
import { useExpertsApi } from '@/api/index'
const { reviewtaskCancelProjects, saveExpertByRule } = useExpertsApi();

const emit = defineEmits(['refresh'])
const { appContext } = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
const automaticTableRef = ref('')
const projectRuleEditDialogRef = ref(null)
const projectAddExpertDialogViewRef = ref(null)
// 查询参数
let queryParams = reactive({
  taskId: undefined,
  keyWords: undefined,
  type: 0,
})
let rulesArray = ref([])
const taskName = ref(null)
const visible = ref(false)
const title = ref('自动分配结果列表')
const tableColumns = reactive([
  {
    field: 'adName', title: '地区名称', width: 250, align: 'left',
  },
  { field: 'agName', title: '单位名称', width: 180, align: 'left', },
  { field: 'proName', title: '项目名称', width: 250, align: 'left', cellRender: { name: 'xmYHS' } },
  { field: 'proCode', title: '项目编码', width: 200, align: 'left', },
  {
    field: 'expertList', title: '已分配评审专家', align: 'left', width: 400, showOverflow: false,
    fixed: 'right', slots: { default: 'expertOperation' }, className: 'allot-expert'
  },
])
/** 添加 */
const handleAdd = () => {
  let params = {}
  const seleRows = automaticTableRef.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    globalProxy.$message({ message: `请至少选择一条数据！`, type: "warning" });
    return
  }
  params = {
    taskId: queryParams.taskId,
    applyIds: undefined,
  }
  projectAddExpertDialogViewRef.value.handleOpen(params)
}
/** 规则保存回调 */
const handleRuleSave = (data) => {
  const array = data
  let models = []
  array.forEach(element => {
    let expertList = []
    element.ruleList.forEach(item => {
      item.expertList.forEach((subItem) => {
        expertList.push(subItem)
      })
    })
    models.push(expertList)
  });
  rulesArray.value = data
  const seleRows = automaticTableRef.value.getCheckboxRecords()
  for (let index = 0; index < seleRows.length; index++) {
    const element = seleRows[index]
    const expertList = models[index]
    let array = []
    let expertArray = XEUtils.clone(expertList, true)
    let map = new Map();
    for (let item of expertArray) {
      map.set(item.expertId, item);
    }
    expertArray = [...map.values()];
    array = expertArray
    element.expertList = array
  }
}
/**  专家保存回调 */
const handleSave = (models) => {
  const expertArray = XEUtils.clone(models, true)
  const seleRows = automaticTableRef.value.getCheckboxRecords()
  let applyIdArray = []
  seleRows.forEach(element => {
    applyIdArray.push(element.applyId)
  })
  let expertIdArray = []
  expertArray.forEach(element => {
    expertIdArray.push(element.expertId)
  });
  let params = {}
  params.taskName = taskName.value
  params.taskId = queryParams.taskId
  let applyIds = applyIdArray.join(',')
  let expertIds = expertIdArray.join(',')
  params.applyIds = applyIds
  params.expertIds = expertIds
  projectRuleEditDialogRef.value.handleOpen(params)
}
/** 打开弹出层 */
const handleOpen = (id, name) => {
  visible.value = true
  queryParams.taskId = id
  taskName.value = name
}
/** 关闭弹窗 */
const handleClose = () => {
  visible.value = false
  handleReset()
}
/** 查询 */
const handleSearch = () => {
  automaticTableRef.value.searchEvent()
}
/** 重置 */
const handleReset = () => {
  const defaultParams = automaticTableRef.value.resetEvent()
  Object.assign(queryParams, defaultParams)
}
/** 确认提交 */
const handleConfirm = async (textName) => {
  const seleRows = automaticTableRef.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    globalProxy.$message({ message: `请至少选择一条数据！`, type: "warning" });
    return
  }
  let isValidate = false
  let models = []
  seleRows.forEach((element, index) => {
    let model = {}
    if (rulesArray.value.length >= index + 1) {
      let ruleList = []
      let ruleItem = rulesArray.value[index]
      model.applyId = element.applyId
      model.taskId = queryParams.taskId
      if (element.expertList.length > 0) {
        ruleItem.ruleList.forEach(subItem => {
          let subModel = {}
          subModel.ruleId = subItem.ruleId
          subModel.scoreType = subItem.scoreType
          let expertIdsArray = []
          subItem.expertList.forEach((item) => {
            expertIdsArray.push(item.expertId)
          })
          subModel.expertIds = expertIdsArray.join(',')
          ruleList.push(subModel)
        });
        model.ruleList = ruleList
        models.push(model)
        isValidate = true
      } else {
        isValidate = false
      }
    }
  })
  if (!isValidate) {
    globalProxy.$message({ message: `已分配评审专家数据不能为空！`, type: "warning" });
    return
  }
  visible.value = false
  const params = models
  const result = await saveExpertByRule(params)
  const { data, code, msg } = result
  if (code === 200) {
    globalProxy.$message({ message: `${textName}成功！`, type: "success" });
    emit('refresh')
  } else {
    globalProxy.$message({ message: `${msg}`, type: "error" });
  }
}
/** 取消撤销 */
const handleCancle = (textName) => {
  const seleRows = automaticTableRef.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
    return
  }
  RkConfirmBox({
    title: '提示',
    content: `您确定要${textName}吗？`,
    onSubmit: async function () {
      //获取选中数据
      const applyIdArray = []
      seleRows.forEach(element => {
        applyIdArray.push(element.applyId)
      });
      const applyIds = applyIdArray.join(',')
      const params = { applyIds, taskId: queryParams.taskId }
      const result = await reviewtaskCancelProjects(params)
      const { data, code, msg } = result
      if (code === 200) {
        globalProxy.$message({ message: `${textName}成功！`, type: "success" });
        handleSearch()
      } else {
        globalProxy.$message({ message: `${msg}`, type: "error" });
      }
    },
    onCancel: function () {
    }
  })
}
// 对外暴露方法
defineExpose({
  handleOpen
})
</script>
<style lang="scss" scoped>
:deep(.allot-expert) {
  line-height: 30px;
}
.expert-tag {
  margin-right: 5px;
}
.w-200px {
  width: 200px;
}
</style>